home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / pprint.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  10KB  |  357 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. """Support to pretty-print lists, tuples, & dictionaries recursively.
  5.  
  6. Very simple, but useful, especially in debugging data structures.
  7.  
  8. Classes
  9. -------
  10.  
  11. PrettyPrinter()
  12.     Handle pretty-printing operations onto a stream using a configured
  13.     set of formatting parameters.
  14.  
  15. Functions
  16. ---------
  17.  
  18. pformat()
  19.     Format a Python object into a pretty-printed representation.
  20.  
  21. pprint()
  22.     Pretty-print a Python object to a stream [default is sys.stdout].
  23.  
  24. saferepr()
  25.     Generate a 'standard' repr()-like value, but protect against recursive
  26.     data structures.
  27.  
  28. """
  29. import sys as _sys
  30. import warnings
  31.  
  32. try:
  33.     from cStringIO import StringIO as _StringIO
  34. except ImportError:
  35.     from StringIO import StringIO as _StringIO
  36.  
  37. __all__ = [
  38.     'pprint',
  39.     'pformat',
  40.     'isreadable',
  41.     'isrecursive',
  42.     'saferepr',
  43.     'PrettyPrinter']
  44. _commajoin = ', '.join
  45. _id = id
  46. _len = len
  47. _type = type
  48.  
  49. def pprint(object, stream = None, indent = 1, width = 80, depth = None):
  50.     '''Pretty-print a Python object to a stream [default is sys.stdout].'''
  51.     printer = PrettyPrinter(stream = stream, indent = indent, width = width, depth = depth)
  52.     printer.pprint(object)
  53.  
  54.  
  55. def pformat(object, indent = 1, width = 80, depth = None):
  56.     '''Format a Python object into a pretty-printed representation.'''
  57.     return PrettyPrinter(indent = indent, width = width, depth = depth).pformat(object)
  58.  
  59.  
  60. def saferepr(object):
  61.     '''Version of repr() which can handle recursive data structures.'''
  62.     return _safe_repr(object, { }, None, 0)[0]
  63.  
  64.  
  65. def isreadable(object):
  66.     '''Determine if saferepr(object) is readable by eval().'''
  67.     return _safe_repr(object, { }, None, 0)[1]
  68.  
  69.  
  70. def isrecursive(object):
  71.     '''Determine if object requires a recursive representation.'''
  72.     return _safe_repr(object, { }, None, 0)[2]
  73.  
  74.  
  75. def _sorted(iterable):
  76.     with warnings.catch_warnings():
  77.         if _sys.py3kwarning:
  78.             warnings.filterwarnings('ignore', 'comparing unequal types not supported', DeprecationWarning)
  79.         return sorted(iterable)
  80.  
  81.  
  82. class PrettyPrinter:
  83.     
  84.     def __init__(self, indent = 1, width = 80, depth = None, stream = None):
  85.         '''Handle pretty printing operations onto a stream using a set of
  86.         configured parameters.
  87.  
  88.         indent
  89.             Number of spaces to indent for each level of nesting.
  90.  
  91.         width
  92.             Attempted maximum number of columns in the output.
  93.  
  94.         depth
  95.             The maximum depth to print out nested structures.
  96.  
  97.         stream
  98.             The desired output stream.  If omitted (or false), the standard
  99.             output stream available at construction will be used.
  100.  
  101.         '''
  102.         indent = int(indent)
  103.         width = int(width)
  104.         if not indent >= 0:
  105.             raise AssertionError('indent must be >= 0')
  106.         if not None is None and depth > 0:
  107.             raise AssertionError('depth must be > 0')
  108.         if not None:
  109.             raise AssertionError('width must be != 0')
  110.         self._depth = None
  111.         self._indent_per_level = indent
  112.         self._width = width
  113.         if stream is not None:
  114.             self._stream = stream
  115.         else:
  116.             self._stream = _sys.stdout
  117.  
  118.     
  119.     def pprint(self, object):
  120.         self._format(object, self._stream, 0, 0, { }, 0)
  121.         self._stream.write('\n')
  122.  
  123.     
  124.     def pformat(self, object):
  125.         sio = _StringIO()
  126.         self._format(object, sio, 0, 0, { }, 0)
  127.         return sio.getvalue()
  128.  
  129.     
  130.     def isrecursive(self, object):
  131.         return self.format(object, { }, 0, 0)[2]
  132.  
  133.     
  134.     def isreadable(self, object):
  135.         (s, readable, recursive) = self.format(object, { }, 0, 0)
  136.         if readable:
  137.             pass
  138.         return not recursive
  139.  
  140.     
  141.     def _format(self, object, stream, indent, allowance, context, level):
  142.         level = level + 1
  143.         objid = _id(object)
  144.         if objid in context:
  145.             stream.write(_recursion(object))
  146.             self._recursive = True
  147.             self._readable = False
  148.             return None
  149.         rep = None._repr(object, context, level - 1)
  150.         typ = _type(object)
  151.         sepLines = _len(rep) > self._width - 1 - indent - allowance
  152.         write = stream.write
  153.         if self._depth and level > self._depth:
  154.             write(rep)
  155.             return None
  156.         r = None(typ, '__repr__', None)
  157.         if issubclass(typ, dict) and r is dict.__repr__:
  158.             write('{')
  159.             if self._indent_per_level > 1:
  160.                 write((self._indent_per_level - 1) * ' ')
  161.             length = _len(object)
  162.             if length:
  163.                 context[objid] = 1
  164.                 indent = indent + self._indent_per_level
  165.                 items = _sorted(object.items())
  166.                 (key, ent) = items[0]
  167.                 rep = self._repr(key, context, level)
  168.                 write(rep)
  169.                 write(': ')
  170.                 self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  171.                 if length > 1:
  172.                     for key, ent in items[1:]:
  173.                         rep = self._repr(key, context, level)
  174.                         if sepLines:
  175.                             write(',\n%s%s: ' % (' ' * indent, rep))
  176.                         else:
  177.                             write(', %s: ' % rep)
  178.                         self._format(ent, stream, indent + _len(rep) + 2, allowance + 1, context, level)
  179.                     
  180.                 indent = indent - self._indent_per_level
  181.                 del context[objid]
  182.             write('}')
  183.             return None
  184.         if not None(typ, list) or r is list.__repr__:
  185.             if not issubclass(typ, tuple) or r is tuple.__repr__:
  186.                 if (issubclass(typ, set) or r is set.__repr__ or issubclass(typ, frozenset)) and r is frozenset.__repr__:
  187.                     length = _len(object)
  188.                     if issubclass(typ, list):
  189.                         write('[')
  190.                         endchar = ']'
  191.                     elif issubclass(typ, tuple):
  192.                         write('(')
  193.                         endchar = ')'
  194.                     elif not length:
  195.                         write(rep)
  196.                         return None
  197.                     write(typ.__name__)
  198.                     write('([')
  199.                     endchar = '])'
  200.                     indent += len(typ.__name__) + 1
  201.                     object = _sorted(object)
  202.                     if self._indent_per_level > 1 and sepLines:
  203.                         write((self._indent_per_level - 1) * ' ')
  204.                     if length:
  205.                         context[objid] = 1
  206.                         indent = indent + self._indent_per_level
  207.                         self._format(object[0], stream, indent, allowance + 1, context, level)
  208.                         if length > 1:
  209.                             for ent in object[1:]:
  210.                                 if sepLines:
  211.                                     write(',\n' + ' ' * indent)
  212.                                 else:
  213.                                     write(', ')
  214.                                 self._format(ent, stream, indent, allowance + 1, context, level)
  215.                             
  216.                         indent = indent - self._indent_per_level
  217.                         del context[objid]
  218.                     if issubclass(typ, tuple) and length == 1:
  219.                         write(',')
  220.                     write(endchar)
  221.                     return None
  222.                 None(rep)
  223.                 return None
  224.  
  225.     
  226.     def _repr(self, object, context, level):
  227.         (repr, readable, recursive) = self.format(object, context.copy(), self._depth, level)
  228.         if not readable:
  229.             self._readable = False
  230.         if recursive:
  231.             self._recursive = True
  232.         return repr
  233.  
  234.     
  235.     def format(self, object, context, maxlevels, level):
  236.         """Format object for a specific context, returning a string
  237.         and flags indicating whether the representation is 'readable'
  238.         and whether the object represents a recursive construct.
  239.         """
  240.         return _safe_repr(object, context, maxlevels, level)
  241.  
  242.  
  243.  
  244. def _safe_repr(object, context, maxlevels, level):
  245.     typ = _type(object)
  246.     if typ is str:
  247.         if 'locale' not in _sys.modules:
  248.             return (repr(object), True, False)
  249.         if None in object and '"' not in object:
  250.             closure = '"'
  251.             quotes = {
  252.                 '"': '\\"' }
  253.         else:
  254.             closure = "'"
  255.             quotes = {
  256.                 "'": "\\'" }
  257.         qget = quotes.get
  258.         sio = _StringIO()
  259.         write = sio.write
  260.         for char in object:
  261.             if char.isalpha():
  262.                 write(char)
  263.                 continue
  264.             write(qget(char, repr(char)[1:-1]))
  265.         
  266.         return ('%s%s%s' % (closure, sio.getvalue(), closure), True, False)
  267.     r = None(typ, '__repr__', None)
  268.     if issubclass(typ, dict) and r is dict.__repr__:
  269.         if not object:
  270.             return ('{}', True, False)
  271.         objid = None(object)
  272.         if maxlevels and level >= maxlevels:
  273.             return ('{...}', False, objid in context)
  274.         if None in context:
  275.             return (_recursion(object), False, True)
  276.         context[objid] = None
  277.         readable = True
  278.         recursive = False
  279.         components = []
  280.         append = components.append
  281.         level += 1
  282.         saferepr = _safe_repr
  283.         for k, v in _sorted(object.items()):
  284.             (krepr, kreadable, krecur) = saferepr(k, context, maxlevels, level)
  285.             (vrepr, vreadable, vrecur) = saferepr(v, context, maxlevels, level)
  286.             append('%s: %s' % (krepr, vrepr))
  287.             if readable and kreadable:
  288.                 pass
  289.             readable = vreadable
  290.             if not krecur:
  291.                 if vrecur:
  292.                     recursive = True
  293.                     continue
  294.                 del context[objid]
  295.                 return ('{%s}' % _commajoin(components), readable, recursive)
  296.             if (None(typ, list) or r is list.__repr__ or issubclass(typ, tuple)) and r is tuple.__repr__:
  297.                 if issubclass(typ, list):
  298.                     if not object:
  299.                         return ('[]', True, False)
  300.                     format = None
  301.                 elif _len(object) == 1:
  302.                     format = '(%s,)'
  303.                 elif not object:
  304.                     return ('()', True, False)
  305.                 format = '(%s)'
  306.                 objid = _id(object)
  307.                 if maxlevels and level >= maxlevels:
  308.                     return (format % '...', False, objid in context)
  309.                 if None in context:
  310.                     return (_recursion(object), False, True)
  311.                 context[objid] = None
  312.                 readable = True
  313.                 recursive = False
  314.                 components = []
  315.                 append = components.append
  316.                 level += 1
  317.                 for o in object:
  318.                     (orepr, oreadable, orecur) = _safe_repr(o, context, maxlevels, level)
  319.                     append(orepr)
  320.                     if not oreadable:
  321.                         readable = False
  322.                     if orecur:
  323.                         recursive = True
  324.                         continue
  325.                 del context[objid]
  326.                 return (format % _commajoin(components), readable, recursive)
  327.             rep = None(object)
  328.             if rep:
  329.                 pass
  330.     return (rep, not rep.startswith('<'), False)
  331.  
  332.  
  333. def _recursion(object):
  334.     return '<Recursion on %s with id=%s>' % (_type(object).__name__, _id(object))
  335.  
  336.  
  337. def _perfcheck(object = None):
  338.     import time as time
  339.     if object is None:
  340.         object = [
  341.             ('string', (1, 2), [
  342.                 3,
  343.                 4], {
  344.                 5: 6,
  345.                 7: 8 })] * 100000
  346.     p = PrettyPrinter()
  347.     t1 = time.time()
  348.     _safe_repr(object, { }, None, 0)
  349.     t2 = time.time()
  350.     p.pformat(object)
  351.     t3 = time.time()
  352.     print '_safe_repr:', t2 - t1
  353.     print 'pformat:', t3 - t2
  354.  
  355. if __name__ == '__main__':
  356.     _perfcheck()
  357.